package com.baseweb.webadmin.controller;

import com.baseweb.webadmin.core.constants.BaseState;
import com.baseweb.webadmin.core.constants.MoneyType;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.CitiesUtil;
import com.baseweb.webadmin.core.util.DateUtil;
import com.baseweb.webadmin.core.util.ObjectFormatter;
import com.baseweb.webadmin.service.AccountService;
import com.baseweb.webadmin.service.LogService;
import com.baseweb.webadmin.service.UserOrderService;
import com.baseweb.webadmin.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class BaseController {
    //成功
    public static final String SUCCESS = "SUCCESS";

    //失败
    public static final String FAIL = "FAIL";

    //参数错误
    public static final String INVALID_PARAM = "INVALID_PARAM";

    //重复
    public static final String DUPLICATE = "DUPLICATE";

    //超时
    public static final String SESSION_TIME_OUT = "SESSION_TIME_OUT";

    //没有权限
    public static final String ACCESS_DENY = "ACCESS_DENY";

    //用户不存在
    public static final String USER_NOT_EXIST = "USER_NOT_EXIST";

    //记录不存在
    public static final String RECORD_NOT_EXIST = "RECORD_NOT_EXIST";

    //已锁定
    public static final String LOCKED = "LOCKED";

    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserOrderService userOrderService;

    protected RequestContext getRequestContext(HttpServletRequest request) {
        RequestContext requestContext = new RequestContext(request);
        return requestContext;
    }


    /**
     * 获得当前登录的用户名
     *
     * @return
     */
    public String getUserName() {
        Subject currentUser = SecurityUtils.getSubject();
        return (String) currentUser.getPrincipal();
    }

    public User getCurrentUser() {
        String userName = getUserName();
        if (StringUtils.isNotBlank(userName)) {
            return userService.selectByName(userName);
        } else {
            return null;
        }
    }

    /**
     * 获取客户端的ip地址，如果通过了代理，则获取Header中的X-Forwarded-For值
     * 当X-Forwarded-For值为 remoteAddr,proxy1,proxy2形式时，获取第一个逗号前面的即是客户端ip
     *
     * @param request
     * @return
     */
    protected String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Forwarded-For");
        if (remoteAddr == null || "".equals(remoteAddr)) {
            remoteAddr = request.getRemoteAddr();
        } else {
            if (remoteAddr.indexOf(",") > -1) {
                remoteAddr = remoteAddr.substring(0, remoteAddr.indexOf(","));
            }
        }
        return remoteAddr;
    }

    protected void writeLog(HttpServletRequest request, String logType, String logContent) {
        logService.insert(logType, logContent, getRemoteAddr(request), getUserName());
    }

    protected void writeLog(HttpServletRequest request, String logType, String logContent, String username) {
        logService.insert(logType, logContent, getRemoteAddr(request), username);
    }

    protected void writeMoneyLog(User user, Integer moneyType, BigDecimal amount) {
        ByMoneyLog byMoneyLog = new ByMoneyLog();
        byMoneyLog.setUserId(user.getId());
        byMoneyLog.setAmount(amount);
        byMoneyLog.setMoneyType(moneyType);
        byMoneyLog.setCreateTime(new DateTime());
        byMoneyLog.setUpdateTime(new DateTime());
        accountService.insertMoneyLog(byMoneyLog);

//        user.setMoney(user.getMoney().add(amount));
//        userService.updateUser(user);
    }

    protected void writeMoneyLog(User user, Integer moneyType, String amount) {
        writeMoneyLog(user, moneyType, ObjectFormatter.str2BigDecimal(amount));
    }

    protected void writeCoinsLog(User user, Integer coinType, Integer amount) {
        ByCoinsLog byCoinsLog = new ByCoinsLog();
        byCoinsLog.setUserId(user.getId());
        byCoinsLog.setCoinCount(amount);
        byCoinsLog.setCoinType(coinType);
        byCoinsLog.setCreateTime(new DateTime());
        byCoinsLog.setUpdateTime(new DateTime());
        accountService.insertCoinsLog(byCoinsLog);

//        user.setCoins(user.getCoins() + amount);
//        userService.updateUser(user);
    }

    protected void writeOpenCity(String province, String city, String area, Integer status, Integer open_type){
        User user = getCurrentUser();

        ByOpenCity byOpenCity = new ByOpenCity();
        byOpenCity.setUserId(user.getId());
        byOpenCity.setProvince(province);
        byOpenCity.setCity(city);
        byOpenCity.setArea(area);
        byOpenCity.setStatus(status);
        byOpenCity.setOpenType(open_type);
        byOpenCity.setCreateTime(new DateTime());
        byOpenCity.setUpdateTime(new DateTime());

        userService.insertOpenCity(byOpenCity);
    }

    protected void writeAgentCity(String province, String city, Integer user_id){
        ByUserBizAgentCity byOpenCity = new ByUserBizAgentCity();
        byOpenCity.setUserId(user_id);
        byOpenCity.setProvince(province);
        byOpenCity.setCity(city);
        byOpenCity.setCreateTime(new DateTime());
        byOpenCity.setUpdateTime(new DateTime());

        userService.insertAgentCity(byOpenCity);
    }

    /**
     * 返回操作信息
     *
     * @param response
     * @param msg
     */
    protected void returnMsg(HttpServletResponse response, Object msg) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected Map<String, Object> success(Object data){
        Map json = new HashMap();
        json.put("status", "200");
        json.put("msg", "success");
        json.put("r",data);
        return json;
    }

    protected Map<String, Object> success(Object data, Object more){
        Map json = new HashMap();
        json.put("status", "200");
        json.put("msg", "success");
        json.put("r",data);
        json.put("m", more);
        return json;
    }

    protected Map<String, Object> fail(Object msg){
        Map json = new HashMap();
        json.put("status", "-1");
        json.put("msg", msg);
        json.put("r", "");
        return json;
    }

    protected User currentUser(String token){
        if (StringUtils.isNotBlank(token)) {
            return userService.selectUserByToken(token);
        }
        return null;
    }

    protected boolean validatedRequest(String token){
        if (StringUtils.isBlank(token)){
            return false;
        }else{
            User user = currentUser(token);

            if (user == null || user.getStatus().intValue() == BaseState.DELETE.getCode()){
                return false;
            }
        }
        return true;
    }

    protected Map<String, Object> illegalRequest(){
        return fail("请登录后操作！");
    }
}
